package org.jeecg.modules.controller.wpatient;

import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.modules.doctor.service.IDoctorRegisterRecordService;
import org.jeecg.common.modules.wx.entity.WxAccount;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.register.entity.RegisterPatient;
import org.jeecg.common.modules.register.service.IRegisterPatientService;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.modules.wx.service.IWxAccountService;
import org.jeecg.modules.data.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import org.jeecg.modules.controller.BaseController;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.weixin4j.spring.WeixinTemplate;

import java.util.List;

/**
 * @Description: register_patient
 * @Author: jeecg-boot
 * @Date:   2021-01-26
 * @Version: V1.0
 */
@Api(tags="register_patient")
@RestController
@RequestMapping("api/v1/registerPatient")
@Slf4j
public class RegisterPatientController extends BaseController {
	@Autowired
	private IRegisterPatientService registerPatientService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private IWxUserinfoService wxUserinfoService;
	@Resource
	private IWxAccountService wxAccountService;
	@Resource
	private WeixinTemplate weixinTemplate;

	/**
	 * 患者列表
	 * @param openid
	 * @return
	 */
	@GetMapping("/list")
	public Result<?> getPatientListByOpenId(@RequestParam String openid) {
//		 String openId = null;
//		 try{
//			 if(Objects.nonNull(getOpenId())){ openId = getOpenId(); }
//		 } catch (Exception e){
//			 log.error("getOpenId()获取信息失败",e);
//		 }
//		 if(Objects.isNull(openId)){
//			 openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
//		 }
//		 log.info("openId：{}",openId);
////		 String openId = this.openId;
//
		WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(openid); //获取微信用户
		if(Objects.isNull(wxUserinfo)){
			return Result.error("您的信息错误，请重新登录!");
		}


		//获者当前用户患者列表
		List<RegisterPatient> patientList = registerPatientService.getPatientsByOpenid(wxUserinfo.getId());
		//检查该用户名下的患者是否曾经挂过号

		return Result.ok(patientList);
	}

	/**
	 * 患者详情
	 * @param patientId
	 * @param req
	 * @return
	 */
	@GetMapping("/detail")
	public Result<?> detail(@RequestParam("patientId") String patientId, HttpServletRequest req) {
		String openId = null;
		try{
			if(Objects.nonNull(getOpenId())){ openId = getOpenId(); }
		} catch (Exception e){
			log.error("getOpenId()获取信息失败",e);
		}
		if(Objects.isNull(openId)){
			openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
		}
		log.info("openId：{}",openId);
//		 String openId = this.openId;


		WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(openId); //获取微信用户
		if(Objects.isNull(wxUserinfo)){
			return Result.error("您的信息错误，请重新登录!");
		}

		RegisterPatient patient = registerPatientService.getPatient(wxUserinfo.getId(),patientId);
		if(Objects.isNull(patient)){
			return Result.error("该患者不是您创建，无权查看!");
		}
		return Result.ok(patient);
	}
	/**
	 * 患者详情
	 * @param patientId
	 * @param req
	 * @return
	 */
	@GetMapping("/detailNew")
	public Result<?> detailNew(@RequestParam("patientId") String patientId,@RequestParam("openid") String openid, HttpServletRequest req) {
		String openId = openid;
//		try{
//			if(Objects.nonNull(getOpenId())){ openId = getOpenId(); }
//		} catch (Exception e){
//			log.error("getOpenId()获取信息失败",e);
//		}
		if(Objects.isNull(openId)){
			openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
		}
		log.info("openId：{}",openId);
//		 String openId = this.openId;


		WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(openId); //获取微信用户
		if(Objects.isNull(wxUserinfo)){
			return Result.error("您的信息错误，请重新登录!");
		}

		RegisterPatient patient = registerPatientService.getPatient(wxUserinfo.getId(),patientId);
		if(Objects.isNull(patient)){
			return Result.error("该患者不是您创建，无权查看!");
		}
		return Result.ok(patient);
	}
	/**
	 * 患者信息保存
	 * @param registerPatient
	 * @return
	 */
	@PostMapping("/registerSave")
	public Result<?> registerSave(@RequestBody RegisterPatient registerPatient, HttpServletRequest req){
		log.info("--------------进入微信挂号建档保存registerSave---------------------" +registerPatient);
		WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(registerPatient.getWxUserinfoId()); //获取微信用户
		if(wxUserinfo == null){
			WxUserinfo wxUserinfo1 = new WxUserinfo();
			String uuid = IdUtil.fastUUID();
			wxUserinfo.setId(uuid);
			wxUserinfo.setNickname("微信用户");
			wxUserinfo.setSex(0);
			wxUserinfo.setHeadimgurl("");
			wxUserinfo.setOpenid(registerPatient.getWxUserinfoId());
			WxUserinfo isHave = wxUserinfoService.getByOpenid(registerPatient.getWxUserinfoId());
			if(isHave==null ||"".equals(isHave.getOpenid()) ){
				registerPatient.setWxUserinfoId(uuid);
				WxAccount wxAccount = wxAccountService.getByAppid(weixinTemplate.getWeixinConfig().getAppid());
				wxUserinfo.setWxAccountId(wxAccount.getAccountId());
				wxUserinfoService.save(wxUserinfo);
			}
		}
		try {
			String pinyin = PinyinUtil.getPinyin(registerPatient.getName(),"");
			String first = PinyinUtil.getFirstLetter(registerPatient.getName(),"");
			if (first.length() > 0){
				first = first.substring(0,1);
			}
			registerPatient.setFirstChar(first);
			registerPatient.setPyinShort(pinyin);
		} catch (Exception e) {
			log.error("获取患者拼音失败{}",registerPatient.getName(),e);
		}
		try{
			registerPatient.setWxUserinfoId(wxUserinfo.getId());
		}catch (Exception e){
			log.error("请先关注大医智慧公众号");
		}

		log.info("患者数据：{}",registerPatient);

		if(Objects.isNull(registerPatient.getId()) || registerPatient.getId().equals("")){
			if(registerPatientService.save(registerPatient)){
				return Result.ok("创建成功！");
			}else{
				return Result.error("创建失败！");
			}
		}else{
			if(registerPatientService.updateById(registerPatient)){
				return Result.ok("编辑成功！");
			}else{
				return Result.error("编辑失败！");
			}
		}
	}

	/**
	 * 删除
	 * @param patientId
	 * @return
	 */
	@GetMapping("/delete")
	public Result<?> delete(@RequestParam String patientId, HttpServletRequest req,String openid){

		WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(openid); //获取微信用户
		RegisterPatient patient = registerPatientService.getPatient(wxUserinfo.getId(),patientId);
		if(Objects.isNull(patient)){
			return Result.error("该档案不是您本人的，无权删除!");
		}
		patient.setDeleteStatus(1);
		boolean res = registerPatientService.updateById(patient);
		if(res){
			return Result.ok("删除成功！");
		}else{
			return Result.error("删除失败！");
		}
	}
}
